/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package routing;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Paweł
 */
public class PrivateKeysStore {

    private final String filename = "./commdatpku.data";

    private Map<String, PrivateKey> usersKeys;

    public PrivateKeysStore() {
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
            usersKeys = (Map<String, PrivateKey>) ois.readObject();
            ois.close();
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            usersKeys = new HashMap<String, PrivateKey>();
        }
    }

     public PrivateKey getPrivateKey(String username) {
        synchronized (this) {
            return usersKeys.get(username);
        }
    }

     public void insert(String username, PrivateKey privateKey) {
        try {
            usersKeys.put(username, privateKey);
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
            oos.writeObject(usersKeys);
            oos.close();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

}
